<?php
header("Access-Control-Allow-Origin: http://localhost:9528");

// header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, "Msg" => "连接错误: " . $conn->connect_error]));
}
$data = json_decode(file_get_contents("php://input"), true);

$oldPassword = $data['oldPassword'];
$newPassword = $data['newPassword'];

if (isset($newPassword) && isset($oldPassword)) {
    // echo "select * from users where uname ='{$username}' and password = '{$oldPassword}'";
    $sql = "select * from users where uname = '{$username}'";
    $stmt = $conn->prepare($sql);
    if ($stmt->execute()) {
        if ($rs = $stmt->get_result()) {

            if ($row = $rs->fetch_assoc()) {
                // echo '有';
                // print_r($row);
                $dbpwd = $row['password'];
                if ($dbpwd == $oldPassword) {
                    $sql1 = "UPDATE users SET password = '{$newPassword}' WHERE uname ='{$username}'";
                    //     // echo $sql1;
                    if ($conn->query($sql1)) {
                        echo json_encode(['Code' => 200, 'Msg' => '修改密码成功', 'Ret' => 'True', 'Data' => null]);
                    }
                } else {
                    // echo '错误';
                    echo json_encode(['Code' => 500, 'Msg' => '旧密码错误，请重新输入', 'Ret' => 'False', 'Data' => null]);
                }
            } else {
                // echo "没有";
            }
        }
    }
}
